﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Data.SqlClient;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.IO;
using System.Text.RegularExpressions;

namespace WindowsFormsApplication1
{
    public partial class DataConfigForm : Form
    {
        public DataConfigForm()
        {
            InitializeComponent();
        }

        private void DataConfigForm_Load(object sender, EventArgs e)
        {
            readfile();
        }

        private bool validateIP(string s)
        {
            Regex reg = new Regex(@"^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$");
            Match m = reg.Match(s);
            return m.Success;

        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (this.textBox1.Text == "")
            {
                MessageBox.Show("请输入IP地址");
                return;
            }

            if (!validateIP(this.textBox1.Text))
            {
                MessageBox.Show("请确保IP格式正确");
                return;
            }

            if (this.textBox2.Text == "")
            {
                MessageBox.Show("请输入端口号");
                return;
            }
            if (this.textBox3.Text == "")
            {
                MessageBox.Show("请输入数据库名称");
                return;
            }
            if (this.textBox4.Text == "")
            {
                MessageBox.Show("请输入登陆用户");
                return;
            }

            string s = "Data Source=" + textBox1.Text.Trim() + "," + textBox2.Text.Trim() + ";Initial Catalog=" + textBox3.Text.Trim() +
             ";User ID=" + textBox4.Text.Trim() + ";Password=" + textBox5.Text + ";";

            if (File.Exists("Monitor.exe.config"))
            {
                XmlDocument doc = new XmlDocument();
                doc.Load("Monitor.exe.config");
                XmlNodeList nodeList = doc.SelectNodes("/configuration/connectionStrings/add");


                XmlElement xe = (XmlElement)nodeList[0];
                xe.SetAttribute("connectionString", s);
                doc.Save("Monitor.exe.config");
                UserLog.connectionstring = s;
                Console.WriteLine(s);
            }
            else
            {
                XmlWriterSettings mySettings = new XmlWriterSettings();
                mySettings.Indent = true;//是否进行缩进
                mySettings.IndentChars = ("    ");

                XmlWriter myWriter = XmlWriter.Create("Monitor.exe.config", mySettings);

                myWriter.WriteStartElement("configuration");
                myWriter.WriteStartElement("configSections");
                myWriter.WriteEndElement();
                myWriter.WriteStartElement("connectionStrings");
                myWriter.WriteStartElement("add");
                myWriter.WriteStartAttribute("name");
                myWriter.WriteValue("WindowsFormsApplication1.Properties.Settings.MONITOR_DBConnectionString1");
                myWriter.WriteStartAttribute("connectionString");
                myWriter.WriteValue(s);
                myWriter.WriteStartAttribute("providerName");
                myWriter.WriteValue("System.Data.SqlClient");
                myWriter.WriteEndAttribute();

                myWriter.WriteEndElement();
                myWriter.WriteEndElement();
                myWriter.WriteEndElement();

                myWriter.Flush();
            }
            
            

            MessageBox.Show("配置修改成功，请重启程序！", "数据库连接", MessageBoxButtons.OK, MessageBoxIcon.Information);
             
            DialogResult r = MessageBox.Show("是否立即重启？", "数据库连接", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (r == DialogResult.Yes)
            {
                Application.Restart();
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            
        }

        private void parsestring(string s)
        {
            try
            {
                int len = s.Length;
                int index = s.IndexOf(';');
                string temp = s.Substring(12, index - 12);
                //Console.WriteLine(temp);

                int index1 = s.IndexOf(',');
                temp = s.Substring(12, index1 - 12);
                //Console.WriteLine(temp);
                textBox1.Text = temp;


                temp = s.Substring(index1 + 1, index - index1 - 1);
                textBox2.Text = temp;
                //     Console.WriteLine(temp);

                string s1 = s.Substring(index + 1, len - index - 1);
                //      Console.WriteLine(s1);
                len = s1.Length;

                index = s1.IndexOf(';');
                temp = s1.Substring(16, index - 16);
                textBox3.Text = temp;
                //      Console.WriteLine(temp);

                s1 = s1.Substring(index + 1, len - index - 1);
                //      Console.WriteLine(s1);
                len = s1.Length;

                index = s1.IndexOf(';');
                temp = s1.Substring(8, index - 8);
                textBox4.Text = temp;
                //      Console.WriteLine(temp);

                s1 = s1.Substring(index + 1, len - index - 1);
                //     Console.WriteLine(s1);
                len = s1.Length;

                index = s1.IndexOf(';');
                temp = s1.Substring(9, index - 9);
                textBox5.Text = temp;
                //    Console.WriteLine(temp);
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message, "错误！", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void readfile()
        {
            XmlDocument doc = new XmlDocument();
            if (File.Exists("Monitor.exe.config"))
            {
                doc.Load("Monitor.exe.config");
            }
            else
            {
                return;
            }
            
            XmlNodeList nodeList = doc.SelectNodes("/configuration/connectionStrings/add");
            string s = nodeList[0].Attributes[1].Value;

            if (s == "")
            {
                return;
            }

            parsestring(s);
            
        }

        private void button1_MouseEnter(object sender, EventArgs e)
        {
            button1.BackColor = Color.LightBlue;
        }

        private void button1_MouseLeave(object sender, EventArgs e)
        {
            button1.BackColor = Color.White;
        }

        private void button1_MouseDown(object sender, MouseEventArgs e)
        {
            button1.BackColor = Color.Orange;
        }

        private void button2_MouseDown(object sender, MouseEventArgs e)
        {
            button2.BackColor = Color.Orange;
        }

        private void button2_MouseEnter(object sender, EventArgs e)
        {
            button2.BackColor = Color.LightBlue;
        }

        private void button2_MouseLeave(object sender, EventArgs e)
        {
            button2.BackColor = Color.White;
        }

        private void button2_Click_1(object sender, EventArgs e)
        {

            string strConnection = "server=" + textBox1.Text + "," + textBox2.Text + ";"
                                 + "user id=" + textBox4.Text + ";" + "pwd=" + textBox5.Text
                                 + ";" + "database=" + textBox3.Text;

            SqlConnection con = new SqlConnection(strConnection);

            try
            {
                con.Open();
                MessageBox.Show("连接成功！", "数据库连接", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception Ex)
            {
                MessageBox.Show("连接失败！"+ Ex.Message, "数据库连接", MessageBoxButtons.OK, MessageBoxIcon.Error);

            }
            finally
            {
                con.Close();
            }


        }

    }
}
